package leetcode.code1696;

import java.util.Deque;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int maxResult(int[] nums, int k) {
		int len = nums.length;
		int[] dp = new int[len];
		dp[len - 1] = nums[len - 1];
		Deque<Integer> queue = new LinkedList<>();
		queue.add(len - 1);
		for (int i = len - 2; i >= 0; i--) {
			int r = i + k;// 来到i位置右侧最远能跳到r
			if (r < queue.getFirst()) {// 队内最远位置是否可达
				queue.pollFirst();// 这个最大点是无法从i跳到的位置
			}
			dp[i] = dp[queue.getFirst()] + nums[i];
			// 大弹小，小压大，队内单调递减，队头最大，即有效区间内最大值就是队头
			while (!queue.isEmpty() && dp[queue.getLast()] <= dp[i]) {
				queue.pollLast();
			}
			queue.add(i);
		}
		return dp[0];
	}

	@Override
	public void debug4() {
		H.compare(-1, this.maxResult(H.str2array3("[0,-1,-2,-3,1]"), 2));
		H.compare(17, this.maxResult(H.str2array3("[10,-5,-2,4,0,3]"), 3));
		H.compare(-40, this.maxResult(H.str2array3("[40,30,-100,-100,-10,-7,-3,-3]"), 2));
		H.compare(7, this.maxResult(H.str2array3("[1,-1,-2,4,-7,3]"), 2));
		H.compare(0, this.maxResult(H.str2array3("[1,-5,-20,4,-1,3,-6,-3]"), 2));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
